import { GradeIEvent } from '@/pages/BigData/components/EventInfo';
import { StationRunState } from '@/pages/BigData/components/OperatorRuning';
import { StationHistoryIncomeData } from '@/pages/BigData/components/RevenueRanking';
import { StationChargeData } from '@/pages/BigData/components/StationChargeData';
import { StationChargeHistoryData } from '@/pages/BigData/components/StationChargeRank';
import { StationEfficiencyData } from '@/pages/BigData/components/StationConversionEfficiency';
import { StationIncomeData } from '@/pages/BigData/components/StationDailyIncome';
import { TooltipData } from '@/pages/BigData/components/StationDataMap';
import { StationTotalIncomeData } from '@/pages/BigData/components/StationIncome';
import { IEvent } from '@/pages/BigData/components/StationOverview';
import { StationOverviewData } from '@/pages/BigData/components/StationPowerOverview';
import { StationTypeData } from '@/pages/BigData/components/StationType';
import {
  overviewControllerGetAllStationMapDatas,
  overviewControllerGetAllStationOverview,
  overviewControllerGetDayEnergy,
  overviewControllerGetDayIncome,
  overviewControllerGetEventDatas,
  overviewControllerGetHistoryEnergy,
  overviewControllerGetHistoryIncome,
  overviewControllerGetStationEfficiency,
  overviewControllerGetStationRunState,
  overviewControllerGetStationRunStatus,
  overviewControllerGetStations,
} from '@/services/ess/mainpageOverview';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { useIntl } from '@umijs/max';
import { useEffect, useState } from 'react';
import { formatPower, getEventType } from './tools';

export interface StationLocationData {
  stationAddress: string;
  stationLongitude: number;
  stationLatitude: number;
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface HomeDataProps {
  StationOverviewPowerData: StationOverviewData[];
  StationOverviewData: IEvent[];
  StationEffectData: StationEfficiencyData[];
  StationRunStateData: StationRunState[];
  StationWarningData: GradeIEvent[];
  StationAllChargeData: StationChargeData[];
  StationMonthChargeData: StationChargeData[];
  StationYearChargeData: StationChargeData[];
  StationAllIncomeData: StationIncomeData[];
  StationMonthIncomeData: StationIncomeData[];
  StationYearIncomeData: StationIncomeData[];
  StationChargeHistoryData: StationChargeHistoryData[];
  StationHistoryAllIncomeData: StationHistoryIncomeData[];
  StationTotalIncomeData: StationTotalIncomeData;
  StationTotalNumber: StationTypeData[];
  StationTooltipData: TooltipData[];
  StationStatusData: StationTypeData[];
}

export const useFetchStationData = (stationId?: string | number) => {
  const intl = useIntl();
  const [homeData, setHomeData] = useState<HomeDataProps>({
    StationOverviewPowerData: [],
    StationOverviewData: [],
    StationEffectData: [],
    StationRunStateData: [],
    StationWarningData: [],
    StationAllChargeData: [],
    StationAllIncomeData: [],
    StationChargeHistoryData: [],
    StationHistoryAllIncomeData: [],
    StationTotalIncomeData: {},
    StationTotalNumber: [],
    StationTooltipData: [],
    StationStatusData: [],
    StationMonthChargeData: [],
    StationYearChargeData: [],
    StationMonthIncomeData: [],
    StationYearIncomeData: [],
  });

  useEffect(() => {
    const fetchAllStationData = async () => {
      try {
        const allDataResponse = await overviewControllerGetAllStationOverview();

        if (allDataResponse.success) {
          const data = allDataResponse.data;
          const allData = {
            stationAmount: data?.stationCount,
            stationInstallation: data?.totalCapacity,
            stationPower: data?.totalPower,
            stationCharge: data?.totalChargeEnergy,
            stationDisCharge: data?.totalDischargeEnergy,
          };
          setHomeData((prev) => ({
            ...prev,
            StationOverviewPowerData: [allData],
          }));
        }
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    };

    const fetchAllStationState = async () => {
      try {
        const stationStatusTypeDict = await fetchDictInfo(DATABASE_TYPE_ENUM.STATION_RUN_STATUS);
        const allStateResponse = await overviewControllerGetStations({ size: '5' });

        if (allStateResponse.success && allStateResponse.data) {
          const data = allStateResponse.data;

          // 构建 allState 数组
          const allState = data.slice(0, 4).map((station, index: number) => {
            // 确保类型一致
            const runStatus = String(station.runStatus);
            const stationState =
              stationStatusTypeDict.find((item) => item.value === runStatus)?.label || '--';

            return {
              stationRank: index + 1,
              stationName: station.stationName,
              stationCapacity: `${station.capacity} ${station.capacityUnit}`,
              stationState: stationState,
            };
          });

          // 更新状态
          setHomeData((prev) => ({
            ...prev,
            StationOverviewData: allState,
          }));
        }
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    };

    const fetchAllEfficicency = async () => {
      try {
        const allEffectDataResponse = await overviewControllerGetStationEfficiency({ size: '3' });
        if (allEffectDataResponse.success && allEffectDataResponse.data) {
          const data = allEffectDataResponse.data ?? [];
          const allEffect = data.slice(0, 3).map((station: any) => ({
            stationId: station?.stationId ?? '',
            convertRatio: station?.convertRatio ?? 0,
            stationName: station?.stationName ?? '',
          }));
          setHomeData((prev) => ({
            ...prev,
            StationEffectData: allEffect,
          }));
        }
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    };

    const fetchAllRunTime = async () => {
      try {
        const allRunResponse = await overviewControllerGetStationRunState({ size: '3' });
        if (allRunResponse.success && allRunResponse.data) {
          const data = allRunResponse.data ?? [];
          const allRunTime = data.slice(0, 3).map((station: any) => ({
            name: station?.stationName ?? '',
            runtime: parseFloat((Number(station?.durationTime) ?? 0).toFixed(2)),
          }));
          setHomeData((prev) => ({
            ...prev,
            StationRunStateData: allRunTime,
          }));
        }
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    };

    const fetchAllWarning = async () => {
      try {
        const allWarningResponse = await overviewControllerGetEventDatas({ size: 10 });
        if (allWarningResponse.success && allWarningResponse.data) {
          const data = allWarningResponse.data ?? [];
          const allWarning = data.slice(0, 10).map((station: any, index: number) => ({
            eventRank: index + 1,
            eventType: getEventType(String(station?.eventType)) ?? '--',
            eventName: station.eventName ?? '--',
            eventLocation: station?.location ?? '--',
          }));
          setHomeData((prev) => ({
            ...prev,
            StationWarningData: allWarning,
          }));
        }
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    };
    const fetchAllCharge = async () => {
      try {
        const allChargeResponse = await overviewControllerGetDayEnergy({ type: '1' });
        if (allChargeResponse.success && allChargeResponse.data) {
          const data = allChargeResponse.data ?? [];
          const allCharge = data.slice(0, 7).map((station: any) => ({
            date: station.date,
            chargeEnergy: station?.chargeEnergy ?? '--',
            dischargeEnergy: station?.dischargeEnergy ?? '--',
          }));
          setHomeData((prev) => ({
            ...prev,
            StationAllChargeData: allCharge,
          }));
        }
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    };
    const fetchMonthCharge = async () => {
      try {
        const allChargeResponse = await overviewControllerGetDayEnergy({ type: '2' });
        if (allChargeResponse.success && allChargeResponse.data) {
          const data = allChargeResponse.data ?? [];
          const allCharge = data.slice(0, 12).map((station: any) => ({
            date: station.date,
            chargeEnergy: station?.chargeEnergy ?? '--',
            dischargeEnergy: station?.dischargeEnergy ?? '--',
          }));
          setHomeData((prev) => ({
            ...prev,
            StationMonthChargeData: allCharge,
          }));
        }
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    };
    const fetchYearCharge = async () => {
      try {
        const allChargeResponse = await overviewControllerGetDayEnergy({ type: '3' });
        if (allChargeResponse.success && allChargeResponse.data) {
          const data = allChargeResponse.data ?? [];
          const allCharge = data.slice(0, 7).map((station: any) => ({
            date: station.date,
            chargeEnergy: station?.chargeEnergy ?? '--',
            dischargeEnergy: station?.dischargeEnergy ?? '--',
          }));
          setHomeData((prev) => ({
            ...prev,
            StationYearChargeData: allCharge,
          }));
        }
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    };
    const fetchAllIncome = async () => {
      try {
        const allIncomeResponse = await overviewControllerGetDayIncome({ type: '1' });
        if (allIncomeResponse.success && allIncomeResponse.data) {
          const data = allIncomeResponse.data ?? [];
          const allIncome = data.slice(0, 7).map((station: any) => ({
            date: station.date,
            income: station?.income ?? '--',
          }));
          setHomeData((prev) => ({
            ...prev,
            StationAllIncomeData: allIncome,
          }));
        }
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    };

    const fetchMonthIncome = async () => {
      try {
        const allIncomeResponse = await overviewControllerGetDayIncome({ type: '2' });
        if (allIncomeResponse.success && allIncomeResponse.data) {
          const data = allIncomeResponse.data ?? [];
          const allIncome = data.slice(0, 12).map((station: any) => ({
            date: station.date,
            income: station?.income ?? '--',
          }));
          setHomeData((prev) => ({
            ...prev,
            StationMonthIncomeData: allIncome,
          }));
        }
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    };

    const fetchYearIncome = async () => {
      try {
        const allIncomeResponse = await overviewControllerGetDayIncome({ type: '3' });
        if (allIncomeResponse.success && allIncomeResponse.data) {
          const data = allIncomeResponse.data ?? [];
          const allIncome = data.slice(0, 7).map((station: any) => ({
            date: station.date,
            income: station?.income ?? '--',
          }));
          setHomeData((prev) => ({
            ...prev,
            StationYearIncomeData: allIncome,
          }));
        }
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    };

    const fetchHistoryCharge = async () => {
      try {
        const allHistoryResponse = await overviewControllerGetHistoryEnergy({ size: '7' });
        if (allHistoryResponse.success && allHistoryResponse.data) {
          const data = allHistoryResponse.data ?? [];
          const allHistory = data.slice(0, 5).map((station: any) => ({
            stationId: station.stationId,
            totalChargeEnergy: station?.totalChargeEnergy ?? '--',
            totalDischargeEnergy: station?.totalDischargeEnergy ?? '--',
            stationName: station.stationName,
          }));
          setHomeData((prev) => ({
            ...prev,
            StationChargeHistoryData: allHistory,
          }));
        }
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    };

    const fetchHistoryIncome = async () => {
      try {
        const allHistoryIncomeResponse = await overviewControllerGetHistoryIncome({ size: '7' });
        if (allHistoryIncomeResponse.success && allHistoryIncomeResponse.data) {
          const data = allHistoryIncomeResponse.data ?? [];
          const allHistoryIncome = data.slice(0, 5).map((station: any) => ({
            stationId: station.stationId,
            income: station?.income ?? '--',
            stationName: station.stationName,
          }));
          setHomeData((prev) => ({
            ...prev,
            StationHistoryAllIncomeData: allHistoryIncome,
          }));
        }
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    };

    const fetchTotalIncome = async () => {
      try {
        const totalIncomeResponse = await overviewControllerGetAllStationOverview();
        if (totalIncomeResponse.success && totalIncomeResponse.data) {
          const data = totalIncomeResponse.data ?? [];
          const totalIncome = {
            CumulativeIncome: parseFloat((Number(data?.totalIncome) ?? 0).toFixed(2)),
            TodayIncome: parseFloat((Number(data?.dayIncome) ?? 0).toFixed(2)),
          };
          setHomeData((prev) => ({
            ...prev,
            StationTotalIncomeData: totalIncome,
          }));
        }
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    };

    const fetchStaionNumber = async () => {
      try {
        // 获取站点类型字典信息
        const stationTypeDict = await fetchDictInfo(DATABASE_TYPE_ENUM.SITE_TYPE);
        const totalStationNumberResponse = await overviewControllerGetAllStationOverview();

        if (totalStationNumberResponse.success && totalStationNumberResponse.data) {
          const data = totalStationNumberResponse.data.types ?? [];

          // 构建 StationTotalNumber 数组
          const StationTotalNumber = data.map((station) => {
            // 确保类型一致
            const stationType = String(station.type);
            const stationTypeName =
              stationTypeDict.find((item) => item.value === stationType)?.label || '--';

            return {
              stationTypeName: stationTypeName,
              num: (station?.count as number) ?? '--',
              stationProportion: (station.ratio as unknown as number) ?? '--',
            };
          });

          // 更新状态
          setHomeData((prev) => ({
            ...prev,
            StationTotalNumber: StationTotalNumber,
          }));
        }
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    };

    const fetchStationMap = async () => {
      const mapDataResponse = await overviewControllerGetAllStationMapDatas({
        parent: '',
        level: '',
      });
      if (mapDataResponse.success && mapDataResponse.data) {
        const data = mapDataResponse.data ?? [];
        const tipData = data.map((station: any) => {
          const formattedCapacity = formatPower(station.capacity, false);
          const formattedPower = formatPower(station.ratedPower, true);
          const formattedDischargedEnergy = formatPower(station.dischargedEnergy, false);
          const formattedChargedEnergy = formatPower(station.chargedEnergy, false);

          return {
            name: station.address,
            address: station.address,
            stationName: station.stationName,
            online: station.online ?? false,
            date: station.startRunTime ?? '--',
            tenant: station.tenantName ?? '--',
            capacity: formattedCapacity.value + (station.capacityUnit ?? formattedCapacity.unit),
            power: formattedPower.value + (station.ratedPowerUnit ?? formattedPower.unit),
            efficiency:
              station.conversion !== null && station.conversion !== undefined
                ? station.conversion + '%'
                : '--',
            loop:
              station.loopCount !== null && station.loopCount !== undefined
                ? station.loopCount + intl.formatMessage({ id: 'bigdata.times' })
                : '--',
            all:
              station.efficiency !== null && station.efficiency !== undefined
                ? station.efficiency + '%'
                : '--',
            charge:
              formattedChargedEnergy.value +
              (station.chargedEnergyUnit ?? formattedChargedEnergy.unit),
            discharge:
              formattedDischargedEnergy.value +
              (station.dischargedEnergyUnit ?? formattedDischargedEnergy.unit),
          };
        });

        // 添加中国的站点总数数据到 tipData 中
        tipData.push({
          name: '中国',
          stationName: '中国站点总数',
          date: '',
          tenant: '',
          capacity: '',
          power: '',
          efficiency: '',
          loop: '',
          all: '',
          charge: '',
          discharge: '',
          online: false,
          address: undefined,
        });

        setHomeData((prev) => ({
          ...prev,
          StationTooltipData: tipData,
        }));
      }
    };

    const fetchStationStatus = async () => {
      try {
        const stationTypeDict = await fetchDictInfo(DATABASE_TYPE_ENUM.STATION_RUN_STATUS);
        const totalStatusResponse = await overviewControllerGetStationRunStatus();

        if (totalStatusResponse.success && totalStatusResponse.data) {
          const data = totalStatusResponse.data ?? [];
          const StationStatus = data.map((station: any) => {
            // 确保类型一致
            const runStatus = String(station.runStatus);
            const stationTypeName =
              stationTypeDict.find((item) => item.value === runStatus)?.label || '--';
            return {
              stationTypeName: stationTypeName,
              num: (station?.count as number) ?? '--',
              stationProportion: (station.ratio as number) ?? '--',
            };
          });

          setHomeData((prev) => ({
            ...prev,
            StationStatusData: StationStatus,
          }));
        }
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    };

    fetchAllStationData();
    fetchAllStationState();
    fetchAllEfficicency();
    fetchAllRunTime();
    fetchAllWarning();
    fetchAllCharge();
    fetchAllIncome();
    fetchHistoryCharge();
    fetchHistoryIncome();
    fetchTotalIncome();
    fetchStaionNumber();
    fetchStationMap();
    fetchStationStatus();
    fetchMonthCharge();
    fetchYearCharge();
    fetchMonthIncome();
    fetchYearIncome();
    // 定义一个函数来执行所有请求
    async function fetchData() {
      try {
        await Promise.all([
          fetchAllStationState(),
          fetchAllEfficicency(),
          fetchAllRunTime(),
          fetchAllWarning(),
          fetchHistoryCharge(),
          fetchHistoryIncome(),
          fetchStaionNumber(),
          fetchStationStatus(),
          fetchMonthCharge(),
        ]);
        console.log('All data fetched successfully');
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    }

    // 定义一个函数来设置每天定时刷新
    function setDailyRefresh() {
      // 计算当前时间到午夜12点的毫秒数
      const now = new Date();
      const midnight = new Date(now);
      midnight.setHours(24, 0, 0, 0); // 设置为午夜12点
      const timeToMidnight = midnight.getTime() - now.getTime();

      // 设置一个定时器在午夜12点执行一次
      setTimeout(() => {
        // 执行一次请求
        fetchData();

        // 设置一个每天执行一次的定时器
        setInterval(fetchData, 24 * 60 * 60 * 1000); // 每天执行一次
      }, timeToMidnight);
    }

    // 调用 setDailyRefresh 函数来设置每天定时刷新
    setDailyRefresh();
    // 设置定时器，每小时刷新日充放电
    // 设置定时器，每小时刷新日收益
    // 设置定时器，每小时刷新总览
    // 设置定时器，每小时刷所有收益统计
    const hourlyIntervalId = setInterval(() => {
      fetchAllCharge();
      fetchAllIncome();
      fetchAllStationData();
      fetchTotalIncome();
    }, 3600000);
    // 设置定时器，每2分钟刷新一次事件信息
    const AllWarningintervalId = setInterval(fetchAllWarning, 120000);
    const fetchStationMapintervalId = setInterval(fetchStationMap, 120000);
    // 组件卸载时清除定时器
    return () => {
      clearInterval(hourlyIntervalId);
      clearInterval(AllWarningintervalId);
      clearInterval(fetchStationMapintervalId);
    };
  }, [stationId]);

  return homeData;
};

export const fetchStationLocation = async (): Promise<StationLocationData[]> => {
  const mapDataResponse = await overviewControllerGetAllStationMapDatas({
    parent: '',
    level: '',
  });
  if (mapDataResponse.success && mapDataResponse.data) {
    const data = mapDataResponse.data ?? [];
    const specialAddresses = [
      '6001 County Rd 700 Columbia City Indiana 46845',
      '14199 Auburn Rd Fort Wayne Indiana 46845',
      '3501 W Dupont Rd, Fort Wayne, IN 46818 USA',
    ];
    const locationData = data
      .map((station: any) => {
        if (
          station.address &&
          station.longitude !== null &&
          station.longitude !== undefined &&
          station.latitude !== null &&
          station.latitude !== undefined
        ) {
          const needsLongitudeAdjustment = specialAddresses.includes(station.address.trim());
          return {
            stationAddress: station.address,
            stationLongitude: needsLongitudeAdjustment
              ? station.longitude + 360
              : station.longitude,
            stationLatitude: station.latitude,
          } as StationLocationData;
        }
        return null;
      })
      .filter((item) => item !== null) as StationLocationData[];

    return locationData;
  }
  return [];
};
